package com.guli.sms.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.guli.sms.service.SmsService;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Map;

/**
 * @author ZHAOZHENYU
 * @since 2022/10/2
 */

@Service
public class SmsServiceImpl implements SmsService {

    // 整合阿里云短信
    @Override
    public boolean sendSms(String phoneNumber, String templateCode, Map<String, Object> param) {

        if (StringUtils.isEmpty(param)) return false;

        DefaultProfile profile = DefaultProfile.getProfile("default",
                "LTAI5t8biZ2mR3NAbmDPrq6S", "GOcu7UTxped63ZsfGYxHg82V2dHtta");
        IAcsClient client = new DefaultAcsClient(profile);

        CommonRequest request = new CommonRequest();
        //request.setProtocol(ProtocolType.HTTPS);
        request.setMethod(MethodType.POST);
        request.setDomain("dysmsapi.aliyuncs.com");
        request.setVersion("2022-10-02");
        request.setAction("SendSms");

        // 设置签名 电话号 模板文字 验证码
        request.putQueryParameter("PhoneNumbers", phoneNumber);
        request.putQueryParameter("SignName", "我的谷粒学院网站");
        request.putQueryParameter("TemplateCode", templateCode);
        request.putQueryParameter("TemplateParam", JSONObject.toJSONString(param));

        try {
            // 响应
            CommonResponse response = client.getCommonResponse(request);
            System.out.println(response.getData());
            return response.getHttpResponse().isSuccess();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return false;
    }
}
